package com.ciwong.epaper.modules.me.util;

import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.volley.AsyncDownload;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.BaseSystem;
import com.ciwong.mobilelib.utils.StatUtils;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ZipHelper;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.zip.ZipUtils;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by res-zwyan on 2015/9/8.
 */
public class MyWorkFileManager {

    public static String TAG = MyWorkFileManager.class.getSimpleName();

    /**
     * 默认保存路径
//     */
//    public static final String DEFUALT_DOWNLOAD_DIR = BaseSystem
//            .getDownloadPath();
//
//    /**
//     * 默认保存路径
//     */
//    public static final String DEFUALT_PACKAGE_DIR = BaseSystem
//            .getPackagesPath();

    private static MyWorkFileManager me;

    private List<DownLoadInfo> mUnCompletedTastList = new ArrayList<>();

    private AsyncDownload mDownLoad;

    private MyWorkFileManager() {
        mDownLoad = AsyncDownload.getInstance();
    }

    public static MyWorkFileManager getInstance() {
        if (me == null) {
            synchronized (MyWorkFileManager.class) {
                if (me == null) {
                    me = new MyWorkFileManager();
                }
            }
        }
        return me;
    }

    public void addWorkToDownLoad(final DownLoadInfo downLoadInfo) {
        addWorkToDownLoad(downLoadInfo, null);
    }

    public void addWorkToDownLoad(final DownLoadInfo downLoadInfo, final BaseCallBack callBack) {
        final String downLoadUrl = downLoadInfo.getUrl();
        final String saveLocalUrl = downLoadInfo.getSavePath();
        if (TextUtils.isEmpty(saveLocalUrl) || TextUtils.isEmpty(downLoadUrl)) {
            // throw new PathIsNotFoundException("downLoadInfo 路径未找到");
            return;
        }
        if (mUnCompletedTastList.indexOf(downLoadInfo) == -1) {
            mUnCompletedTastList.add(downLoadInfo);
        }
        ThreadTask.getInstance().executorOtherThread(new Runnable() {
            public void run() {
                mDownLoad.addTask(downLoadUrl, null, saveLocalUrl,
                        new AsyncDownload.OnProgressUpdate() {
                            @Override
                            public void progressUpdate(long l, long l1, Object o) {
                                // CWLog.d(TAG, "download " + l + " " + l1);
                            }

                            @Override
                            public void error(int i,
                                              AsyncDownload.DownloadTask downloadTask) {
                                // CWLog.e(TAG,
                                // "download err "
                                // + downloadTask.getSavePath());
                                if (null != callBack) {
                                    callBack.failed("下载错误");
                                }
                            }

                            @Override
                            public void completed(
                                    AsyncDownload.DownloadTask downloadTask) {
                                startUpZip(downLoadInfo, callBack);
                            }

                            @Override
                            public void complete(AsyncDownload.DownloadTask task) {
                                startUpZip(downLoadInfo, callBack);
                            }
                        }, saveLocalUrl);
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /**
     * 解压
     */
    private void startUpZip(final DownLoadInfo bean, final BaseCallBack callBack) {
        bean.setStatus(DownloadStatus.STATUS_UPZIPING);
        // EventBus.getDownLoadInstance().post(
        // new EventBusFactory.DownloadEvent(bean, null));
        final String zipAbsName = new File(bean.getSavePath()).getName();

        Log.d("upzip", "##########MyWork startUpZip##########");

        ThreadTask.getInstance().executorOtherThread(new Runnable() {
            @Override
            public void run() {
                // CWLog.e("debug", new File(bean.getSavePath()).exists() + "-"
                // + new Fil;e(bean.getSavePath()).isFile());
                List<String> pathList = ZipUtils
                        .getZIPFiles(new File(bean.getSavePath()));
                String tempPath = "";
                if (pathList.size() > 0) {
                    tempPath = pathList.get(0);
                }
                final String path0 = tempPath;
                CWLog.d(TAG, "startUpZip " + path0);
                ZipHelper.getInstance().addToUpZipTask(bean.getSavePath(),
                        ESystem.getAnswersPath(), new BaseCallBack() {


                            @Override
                            public void failed(int errorCode, Object data) {
                                Log.d("upzip", "##########failed##########"+data.toString());
                                if (null != callBack) {
                                    callBack.failed(errorCode, data);
                                }

                            }

                            @Override
                            public void failed(Object data) {
                                Log.d("upzip", "##########failed##########"+data.toString());
                                String answerPath = ESystem.getAnswersPath();
                                FileUtils.delete(answerPath + File.separator + path0);
                                bean.setStatus(DownloadStatus.STATUS_FAILED);
                                EventBus.getDownLoadInstance().post(
                                        new EventBusFactory.DownloadEvent(bean, null));
                                if (null != callBack) {
                                    callBack.failed(data);
                                }
                            }

                            @Override
                            public void success(Object data) {
                                Log.d("upzip", "##########success##########"+data.toString());
//                                StatUtils.statistics(1, 1, 0, bean.getUrl(), "");

                                bean.setStatus(DownloadStatus.STATUS_COMPLETED);
                                EventBus.getDownLoadInstance().post(
                                        new EventBusFactory.DownloadEvent(bean, null));
                                mUnCompletedTastList.remove(bean);
                                CWLog.d(TAG, "解压完成" + bean.getSavePath());

                                if (null != callBack) {
                                    callBack.success(data);
                                }
                            }
                        });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

    }
}
